package com.chushouya.common.util;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Security;

public abstract class AesUtil {

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * aes解密
     *
     * @param transformation 算法名称，例 AES/CBC/PKCS7Padding
     * @param iv             向量
     * @param key            秘钥
     * @param data           待解密数据
     */
    public static String decode(String transformation, byte[] iv, byte[] key, byte[] data) throws Exception {
        return new String(decodeByte(transformation, iv, key, data), StandardCharsets.UTF_8);
    }

    public static byte[] decodeByte(String transformation, byte[] iv, byte[] key, byte[] data) throws Exception {
        Cipher cipher = Cipher.getInstance(transformation);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv));
        return cipher.doFinal(data);
    }

}
